<?php

namespace app\data\controller\control;
use app\data\model\ControlClaimListModel;
use app\data\model\ControlClaimModel;
use app\data\model\StorehouseDataModel;
use think\admin\Controller;
use app\data\model\StorehouseModel;
use think\admin\extend\CodeExtend;
use think\facade\Db;

/**
 * 领用管理
 * Class Cate
 * @package app\data\controller\shop
 */
class Claim extends Controller
{
    /**
     * 指定数据表
     * @var string
     */
    protected $table = 'SnControlClaim';

    /**
     * 领用管理
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->title = "领用管理";
        // 加载对应数据
        $query = $this->_query($this->table);
        $this->type = $this->request->get('type', 'index');
        if ($this->type === 'index') $query->where(['deleted' => 0]);
        elseif ($this->type === 'recycle') $query->where(['deleted' => 1]);
        else $this->error("无法加载 $this->type 数据列表！");
        $query->equal('status')->like('plan_code,plan_title');
        $userInfo = session('user');
        if($userInfo['id'] == 10000 || $userInfo['authorize'] == 7){
            $query->order('id desc')->page();
        }elseif($userInfo['authorize'] == 4){
            $query->whereIn('admin_id',[$userInfo['id'],0])->order('id desc')->page();
        }else{
            $where = array('admin_id'=>$userInfo['id']);
            $query->where($where)->order('id desc')->page();
        }
    }


    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_page_filter(array &$data)
    {
        // foreach ($data as $k=>$v){
        //     $data[$k]['cate_id'] = 1;
        // }
    }


    /**
     * 添加
     * @auth true
     */
    public function add()
    {
        $this->mode = 'add';
        $this->title = '添加审核数据';
        $this->_form($this->table, 'add');
    }

    /**
     * 编辑
     * @auth true
     */
    public function edit()
    {
        $this->mode = 'edit';
        $this->title = '编辑审核数据';
        $this->_form($this->table, 'edit');
    }



    /**
     * 表单数据处理
     * @param array $data
     */
    protected function _form_filter(array &$data)
    {
        if ($this->request->isGet()) {
            if(isset($data['id'])){
                $this->lists = ControlClaimListModel::where('plan_id',$data['id'])->select()->toArray();
            }
            $this->userId = session('user')['id'];
            $where['is_deleted'] = 0;
            // $this->wuliu_list = Db::name('system_user')->where('authorize','8')->where($where)->field('id,username,nickname')->select()->toArray();
            $this->keshi_list = Db::name('system_user')->where('authorize','2')->where($where)->field('id,nickname,username')->select()->toArray();
            $this->jingyi_list = Db::name('system_user')->where('authorize','4')->where($where)->field('id,nickname,username')->select()->toArray();
        } elseif ($this->request->isPost()){
            if(!isset($data['material_code']) || count($data['material_code'])==0){$this->error('材料列表不可为空');}
            foreach ($data['ex_num'] as $ks => $vs){
                if(!$vs){$this->error($data['material_name'][$ks].'('.$data['material_code'][$ks].')'.'数量不可为0');}
            }
            $userInfo = session('user');
            if(!isset($data['id'])){
                //获取标题
                $data['plan_data_status'] = date('Ym',time());
                $data['plan_title'] = date('Y年m月d日',time()).'领用单';
                // 生成计划ID
                $data['id'] = CodeExtend::uniqidNumber(10,'L');
            }
            $data['admin_id'] = $userInfo['id'];
            $data['admin_name'] = $userInfo['username'];
            //获取提交时间
            // $data['plan_time'] = date('Y-m-d H:i:s',time());
            $data['status'] = 0;
            //查询审核人信息
            $auth_auditing = [$data['keshi_id'],$data['jingyi_id']];
            $userList = Db::name('system_user')->where(['is_deleted'=>0,'status'=>1])->whereIn('id',$auth_auditing)->field('id,username,authorize')->orderRaw("field(authorize,'2','4')")->select();
            //开启事务
            Db::startTrans();
            try{
                //删除计划流程数据
                $time_del = Db::name('sn_control_claim_time')->where('collect_id',$data['id'])->delete();
                if ($time_del === false) {throw new \Exception("服务器错误");}
                // 添加计划表流程数据
                $shenen = array();
                if(count($userList) == 0){
                    $shenen[0]['collect_id'] = $data['id'];
                    $shenen[0]['admin_id'] = 0;
                    $shenen[0]['admin_name'] = '业务科室';
                    $shenen[0]['admin_authorize'] = 2;
                }else{
                    foreach ($userList as $ks=>$vs){
                        $shenen[$vs['authorize']]['collect_id'] = $data['id'];
                        $shenen[$vs['authorize']]['admin_id'] = $vs['id'];
                        $shenen[$vs['authorize']]['admin_name'] = $vs['username'];
                        $shenen[$vs['authorize']]['admin_authorize'] = $vs['authorize'];
                    }
                    $auth_status = in_array(4,array_column($shenen,'admin_authorize'));
                    if(!$auth_status){
                        $shenen[4] = array('collect_id'=>$data['id'],'admin_id'=>0,'admin_name'=>'精益化管理部','admin_nickname'=>'精益化管理部','admin_authorize'=>4);
                    }
                }
//                dump($shenen);die;
                foreach ($userList as $ks=>$vs){
                    $shenen[$vs['authorize']]['collect_id'] = $data['id'];
                    $shenen[$vs['authorize']]['admin_id'] = $vs['id'];
                    $shenen[$vs['authorize']]['admin_name'] = $vs['username'];
                    $shenen[$vs['authorize']]['admin_authorize'] = $vs['authorize'];
                }
                $column = array_column($shenen,'admin_authorize');
                array_multisort($column,SORT_ASC,$shenen);
                //首次审批权限
                $data['plan_status'] = $shenen[0]['admin_authorize'];
                $applyId = Db::name('sn_control_claim_time')->insertAll($shenen);
                // 判断是否添加成功
                if (!$applyId) {throw new \Exception("服务器错误");}
                //删除计划子表数据
                $listDel = Db::name('sn_control_claim_list')->where('plan_id',$data['id'])->delete();
                if ($listDel === false) {throw new \Exception("服务器错误");}
                $StirehouseData = new StorehouseDataModel();
                //获取剩余物资
                $adminStorehouse = Db::name('sn_enter_storehouse_'.$data['admin_id'])->column('material_num','material_code');
                //数组合并array_combine($k,$v)  return $k=>$v
                $combineData= array_combine($data['material_code'],$data['ex_num']);
                foreach ($combineData as $key=>$val){
                    $he = $adminStorehouse[$key] - $val;
                    if($he < 0 ){throw new \Exception($key.'数量不足');}
                    // 减自己库存
                    $res = Db::name('sn_enter_storehouse_'.$data['admin_id'])->where('material_code',$key)->dec('material_num',$val)->update();
                    if (!$res) {throw new \Exception("服务器错误");}
                }
                $cate_list = array();
                //组合数组
                foreach ($data['material_code'] as $k=>$v){
                    $cate_list[$k]['material_code'] = $v;
                    $cate_list[$k]['material_name'] = $data['material_name'][$k];
                    $cate_list[$k]['material_model'] = $data['material_model'][$k];
                    $cate_list[$k]['material_unit'] = $data['material_unit'][$k];
                    $cate_list[$k]['material_price'] = $data['material_price'][$k];
                    $cate_list[$k]['material_num'] = $data['ex_num'][$k];
                    $cate_list[$k]['material_xjprice'] = sprintf("%01.2f", $data['ex_num'][$k] * $data['material_price'][$k]);
                    $cate_list[$k]['plan_id'] = $data['id'];
                    $cate_list[$k]['plan_time'] = date('Y-m-d H:i:s',time());
                    // $cate_list[$k]['cate_id'] = $v['cate_id'];
                    $cate_list[$k]['admin_id'] = $userInfo['id'];
                    $cate_list[$k]['admin_name'] = $userInfo['username'];
                    $cate_list[$k]['status'] = 1;
                }
                // 子表数据添加
                $applyAll = Db::name('sn_control_claim_list')->insertAll($cate_list);
                if (!$applyAll) {throw new \Exception("服务器错误");}
                $data['plan_list'] = json_encode($cate_list,true);
                unset($data['material_code']);
                unset($data['material_name']);
                unset($data['material_model']);
                unset($data['material_unit']);
                unset($data['material_price']);
                unset($data['ex_num']);
                unset($data['cate_id']);
                unset($data['material_xjprice']);
                //主表数据添加
                // $planSave = ControlClaimModel::insertGetId($data);
                // if (!$planSave) {throw new \Exception("服务器错误");}
                // 执行提交操作
                Db::commit();
            }catch(\Exception $e){
                // 回滚事务
                Db::rollback();
                // 获取提示信息
                $this->error($e->getMessage());die;
            }
        }
    }


    /**
     * 查看流程
     * @auth true
     */
    public function ca_detail()
    {
        $plan_list = Db::name('sn_control_claim_time')->where('collect_id',input('id'))->orderRaw("field(admin_authorize,'8','2','4')")->select()->toArray();
        $this->assign('shlist',$plan_list);
        $plan_status = ControlClaimModel::where('id',input('id'))->find()->toArray();
        $this->assign('info',$plan_status);
        $this->fetch();
    }

    /**
     * 物资退还列表
     * @auth true
     */
    public function give_back_index()
    {
        $this->storehouse_list = StorehouseModel::where('deleted',0)->select()->toArray();
        $query = $this->_query('sn_control_claim_list');
        // 列表排序并显示
        $input = input('get.');
        $query->where('plan_id',$input['id']);
        $query->like('material_code,material_name,material_model');
        $query->equal('status')->order('create_at desc')->page();
        $this->fetch();
    }
    /**
     * 物资退还更新
     * @auth true
     */
    public function give_back_num()
    {
        $input = input('post.');
        $ControlClaimList = new ControlClaimListModel();
        $info = $ControlClaimList->where('id',$input['id'])->find()->toArray();
        if(!$info){$this->error('数据不存在');}
        if($info['material_num'] < $input['num']){$this->error('填写数量不可大于原本数量');}
        //开启事务
        Db::startTrans();
        try{
            //库存数量添加
            if(! Db::name('sn_enter_storehouse_'.$info['admin_id'])->where('material_code',$info['material_code'])->inc('material_num',$input['num'])->update()) throw new \Exception("服务器错误");
            $number = $info['material_num']-$input['num'];
            $saveArr = array(
                'material_num'=>$number,
                'material_xjprice'=>round($number * $info['material_price'],2),
            );
            $saveinfo = ControlClaimListModel::where('id',$input['id'])->update($saveArr);
            if($saveinfo === false){return json(['code'=>500,'msg'=>'服务器繁忙']);}
            $admin_user = session('user');
            //添加日志
            $insetAll = array(
                'plan_id'=>$info['plan_id'],
                'remarks'=>'物资退还',
                'key'=>$input['id'],
                'original_num'=>$number,
                'save_num'=>$input['num'],
                'admin_id'=>$admin_user['id'],
                'admin_name'=>$admin_user['username'],
                'time'=>date('Y-m-d H:i:s',time())
            );
            $logId = Db::name('sn_control_claim_log')->insertGetId($insetAll);
            if(!$logId){return json(['code'=>500,'msg'=>'服务器繁忙']);}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());die;
        }
        $this->success('数据更新成功');
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _give_back_index_page_filter(array &$data)
    {
        // dump($data);die;
    }
    /**
     * 表单结果处理
     * @param boolean $result
     */
    protected function _form_result($result)
    {
        if ($result && $this->request->isPost()) {
            $this->success('数据更新成功！');
        }
    }


    /**
     * 详情
     * @auth true
     */
    public function detail()
    {
        $this->title = '详情';
        $data = input('get.');
        $where = array(
            'deleted'=>0,
            'id'=>input('id')
        );
        $info = ControlClaimModel::where($where)->order('id desc')->find();
        $this->assign('info',$info);
        $plan_list = ControlClaimListModel::where('plan_id',$where['id'])->select()->toArray();
        $total = 0;
        if($plan_list){
            foreach ($plan_list as $k=>$v){
                $plan_list[$k]['material_xjprice'] = $v['material_price'] * $v['material_num'];
                $total += $v['material_price'] * $v['material_num'];
            }
        }else{
            $plan_list = [];
        }

        $this->assign('plan_list',$plan_list);
        $this->assign('total',$total);
        $this->fetch();
    }


    /**
     * 删除
     * @auth true
     */
    public function remove()
    {
        $this->_save($this->table, $this->_vali([
            'deleted.in:0,1'  => '状态值范围异常！',
            'deleted.require' => '状态值不能为空！',
        ]), 'id');
    }
}